#!/bin/bash

# Staging环境设置验证脚本
# 验证所有Staging配置是否正确

echo "🔍 验证Staging环境设置..."
echo "========================================"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

PASSED=0
FAILED=0

check_file() {
    if [ -f "$1" ]; then
        echo -e "${GREEN}✅${NC} $1 存在"
        PASSED=$((PASSED + 1))
    else
        echo -e "${RED}❌${NC} $1 不存在"
        FAILED=$((FAILED + 1))
    fi
}

check_directory() {
    if [ -d "$1" ]; then
        echo -e "${GREEN}✅${NC} 目录 $1 存在"
        PASSED=$((PASSED + 1))
    else
        echo -e "${RED}❌${NC} 目录 $1 不存在"
        FAILED=$((FAILED + 1))
    fi
}

echo "\n📁 检查文件和目录..."
check_file "backend/.env.staging"
check_file "nginx-staging.conf"
check_file "deploy-staging.sh"
check_file "scripts/staging/create-staging-database.sql"
check_file "scripts/staging/test-staging-database.js"
check_file "scripts/staging/migrate-to-staging.js"
check_directory "scripts/staging"
check_directory "scripts/staging/management"

echo "\n🔧 检查脚本权限..."
if [ -x "deploy-staging.sh" ]; then
    echo -e "${GREEN}✅${NC} deploy-staging.sh 可执行"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}❌${NC} deploy-staging.sh 不可执行"
    FAILED=$((FAILED + 1))
fi

echo "\n📋 检查环境变量配置..."
if grep -q "NODE_ENV=staging" backend/.env.staging; then
    echo -e "${GREEN}✅${NC} NODE_ENV 配置正确"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}❌${NC} NODE_ENV 配置错误"
    FAILED=$((FAILED + 1))
fi

if grep -q "PORT=3001" backend/.env.staging; then
    echo -e "${GREEN}✅${NC} PORT 配置正确"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}❌${NC} PORT 配置错误"
    FAILED=$((FAILED + 1))
fi

if grep -q "cumrbull_staging" backend/.env.staging; then
    echo -e "${GREEN}✅${NC} 数据库名称配置正确"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}❌${NC} 数据库名称配置错误"
    FAILED=$((FAILED + 1))
fi

echo "\n🌐 检查Nginx配置..."
if grep -q "staging-api.cumrbull.com.sg" nginx-staging.conf; then
    echo -e "${GREEN}✅${NC} Staging API域名配置正确"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}❌${NC} Staging API域名配置错误"
    FAILED=$((FAILED + 1))
fi

if grep -q "127.0.0.1:3001" nginx-staging.conf; then
    echo -e "${GREEN}✅${NC} 上游服务器配置正确"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}❌${NC} 上游服务器配置错误"
    FAILED=$((FAILED + 1))
fi

echo "\n📊 验证总结"
echo "========================================"
echo "通过: $PASSED"
echo "失败: $FAILED"
echo "总计: $((PASSED + FAILED))"

if [ $FAILED -eq 0 ]; then
    echo -e "\n${GREEN}🎉 Staging环境设置验证通过！${NC}"
    echo "\n📋 下一步操作:"
    echo "1. 运行部署脚本: ./deploy-staging.sh"
    echo "2. 配置DNS解析"
    echo "3. 申请SSL证书"
    echo "4. 创建数据库"
    echo "5. 运行连通性测试"
    exit 0
else
    echo -e "\n${RED}❌ Staging环境设置验证失败！${NC}"
    echo "请修复上述问题后重新运行验证。"
    exit 1
fi
